package cn.bocai.pc.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.bocai.pc.dao.VariableMapper;
import cn.bocai.pc.model.BcAdmin;
import cn.bocai.pc.model.BcThumpic;
import cn.bocai.pc.service.BcAdminService;
import cn.bocai.pc.service.BcCollectService;
import cn.bocai.pc.service.BcLinktbleService;
import cn.bocai.pc.service.BcLinktypeService;
import cn.bocai.pc.service.BcPictureService;
import cn.bocai.pc.service.BcThumpicService;
import cn.bocai.pc.service.VariableService;
import cn.bocai.pc.util.MD5Utils;
import cn.bocai.pc.util.UUIDUtils;


@Controller
@RequestMapping("/baUser")
public class UserManageController {
	//注入图片服务
	@Autowired
	BcPictureService bcPictureService;
	@Autowired
	private BcAdminService  BaService;
	@Autowired
	private VariableService variableService;
	@Autowired
	private BcThumpicService bcThumpicService;
	@Autowired
	private BcLinktbleService bcLinktbleService;
	@Autowired
	private BcLinktypeService bcLinktypeService;
	@Autowired
	private BcCollectService bcCollectService;
	//数据字典
	@Autowired
	private  VariableMapper variableDao;
	
	//后台用户登入
	@RequestMapping("/except/login.do")
	public String login(HttpServletRequest request, HttpServletResponse response,BcAdmin baLog,Model m){
		String validateC = (String) request.getSession().getAttribute("baValidateCode"); 
        String veryCode = request.getParameter("securityCode");
		m.addAttribute("skipUrl","/login.jsp");
		 if(veryCode==null||"".equals(veryCode)||"undefined".equals(veryCode)){
        	 m.addAttribute("msg","验证码不能为空");
         }else{        
             if(validateC.equalsIgnoreCase(veryCode)){
			 	 if("".equals(baLog.getUsername())||null==baLog.getUsername()||"".equals(baLog.getPassword())||null==baLog.getPassword()){
		    		 m.addAttribute("msg","用户名或密码不能为空");
		    	 }else{
		    		 baLog.setPassword(MD5Utils.md5(baLog.getPassword()));
		    		 BcAdmin baUserLogin = BaService.selectLogin(baLog);
		        	 if(null==baUserLogin){
		        		 m.addAttribute("msg","用户名或密码错误");
		        	 }else{
		        		 m.addAttribute("msg","登入成功，谢谢！");
		        		 request.getSession().setAttribute("baUserLogin", baUserLogin);
		        		 m.addAttribute("skipUrl","/baSkip/ifram.do");
		        	 }
		          }
             }else{        
                 m.addAttribute("msg","输入验证码有误");
             }        
         }
	 	 /* m.addAttribute("skipUrl","/baSkip/ifram.do");*///改行完成以后要删除 	 
	 	 return "baPage/prompt/publicPrompt";
	}
	
	
	//安全退出
	@RequestMapping("/outLogin.do")
	public String outLogin(HttpServletRequest request,Model m){
		request.getSession().removeAttribute("baUserLogin");
		m.addAttribute("msg","已安全退出，谢谢！");
		m.addAttribute("skipUrl","/login.jsp");
		return "baPage/prompt/publicPrompt";
	}
	//修改密码
	@RequestMapping("/doModifyPwd.do")
	public String doModifyPwd(HttpServletRequest request, HttpServletResponse response,BcAdmin baLog,Model m){
		 String oldPaw =MD5Utils.md5(request.getParameter("password")) ;
    	 String newPaw =MD5Utils.md5(request.getParameter("newPwd"));
		BcAdmin baAttribute = (BcAdmin)request.getSession().getAttribute("baUserLogin");
    	 String password = baAttribute.getPassword();
    	 m.addAttribute("skipUrl","/baSkip/ifram.do");
    	 if(!password.equals(oldPaw)){
    		 m.addAttribute("msg","输入密码有误");
    	 }else{
    		 //修改密码
    		 HashMap<String, Object> map = new HashMap<String, Object>();
    		 map.put("userId", baAttribute.getUserId());
    		 map.put("password", newPaw);
    		int updateUserPaw = BaService.updateUserPaw(map);
    		 if(!"0".equals(updateUserPaw)){
    			 request.getSession().removeAttribute("selectLogin");
    			 m.addAttribute("msg","密码修改成功");
    			 m.addAttribute("skipUrl","/login.jsp");
    		 }
    	 }
    	 return "baPage/prompt/publicPrompt";
	}
	
	/**
	 * 当用点击扫描，通过web服务得出图片服务器的图片名称，
	 * 然后通过图片属性表取出图片属性，插入到图片描述表中
	 * @param colours
	 * @param request
	 * @param m
	 * @return 成功信息，或日志
	 */
	@RequestMapping("/scanPic/{colours}.do")
	public void scanPic(@PathVariable String colours,HttpServletRequest request,HttpServletResponse response,Model m){
		String picPath = variableDao.selectVariable("PIC_bigUrl");//图片存放的目录
		
		if("col".equals(colours)){
			m.addAttribute("skipUrl","/baSkip/colScan.do");
		}else if("black".equals(colours)){
			m.addAttribute("skipUrl","/baSkip/blaScan.do");
		}
		String parYears = request.getParameter("years");
		String parPeriods = request.getParameter("periods");
		PrintWriter out=null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if("请选择".equals(parYears)||"请选择".equals(parPeriods)){
			out.print("0");
		}else{
			//条件不为空，扫描目录
			try {
				//创建cxf服务 
				JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
				//通过webService服务地址，创建客户端
				String variableWSDL=variableService.selectVariable("WS_WSDL");
				 Client client = dcf.createClient(variableWSDL);
				   //给图片服务器发送参数
			       Object[] objects = client.invoke("getDirByImg",parYears,colours,parPeriods,picPath);
					/*System.out.println("成功扫从图片服务器描出-----"+objects.length);*/
			       if(objects.length>0){
			    	   //返回数据处理
			    	@SuppressWarnings("unchecked")
					List<String> list=(List<String>)objects[0];
			    	  if(list.size()>0){
			    		Map map= bcPictureService.scanStorageByThumpic(list,parYears,colours,parPeriods);
			    		out.print("1");
			    	  }else{
				    	out.print("0");
				       }
			       }
			     
			} catch (Exception e) {
				 out.print("0");
				e.printStackTrace();
			}
			
			/* m.addAttribute("msg","扫描成功");*/
		}
		/* return "baPage/prompt/publicPrompt";*/
	}
	
	/**
	 * 当用点击启动何在关闭文件夹监听的时候触发这个方法
	 */
	 @RequestMapping("/MonitorFile/{buttonState}.do")
	 public void MonitorFile(@PathVariable String buttonState,HttpServletRequest request,HttpServletResponse response) throws Exception {
		//创建cxf服务 
			JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
			//通过webService服务地址，创建客户端
			String variableWSDL=variableService.selectVariable("WS_WSDLMonitor");//wsdl地址
			 Client client = dcf.createClient(variableWSDL);
			//设置超时单位为毫秒
				HTTPConduit http = (HTTPConduit) client.getConduit();      
				HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();      
				//httpClientPolicy.setConnectionTimeout(3000);  //连接超时    
				//httpClientPolicy.setAllowChunking(false);    //取消块编码 
				httpClientPolicy.setReceiveTimeout(360000);     //响应超时
				http.setClient(httpClientPolicy);
			 
			 String MonitorPath=variableService.selectVariable("PIC_bigUrl");//扫描的地址
			 String newYear=variableService.selectVariable("year");//最新年份
			 String path=MonitorPath+"/"+newYear;
			 Object[] returnDate = null;
			 if("start".equals(buttonState)){
				 returnDate=client.invoke("startScan",path,"start");
			 } 
			 if("stop".equals(buttonState)){
				 returnDate=client.invoke("startScan",path,"stop"); 
			 }
			 if("psgeStart".equals(buttonState)){
				 returnDate=client.invoke("startScan",path,"psgeStart"); 
			 }
			 String returnState=(String) returnDate[0];
			 response.getWriter().print(returnState);
	 }
	 
	    /**
		 * 删除单挑数据
	     * @throws IOException 
		 */
		@RequestMapping("/delectAlone.do")
		public void delectAlone(HttpServletRequest request,HttpServletResponse response,Model m) throws IOException{
			String id = request.getParameter("uuid");
			String name= request.getParameter("picname");
			String colour= request.getParameter("colour");
			String picCheckout="";
			int delectAlone = bcThumpicService.delectAlone(id);
			String alone= Integer.toString(delectAlone);
			if(1==delectAlone){
			  picCheckout = picCheckout(name,colour);//删除图片服务器中对应的改图片
			}
			response.getWriter().print(alone+'_'+picCheckout);
		}
		  /**
			* 批量删除
			* @throws IOException 
		  */
		@RequestMapping("/delectAll.do")
		public void delectAll(HttpServletRequest request,HttpServletResponse response,Model m) throws IOException{
			String[] id = request.getParameter("uuid").split(",");
			for(int i=0;i<id.length;i++){
				bcThumpicService.delectAlone(id[i]);
			}
			response.getWriter().print("succeed");
		}		
		//删除图片服务器上的图片
		public String picCheckout(String name,String colour) {
			String colours=("1".equals(colour))?"col":"black";
			String picUrl=variableService.selectVariable("PIC_FileExist");//回去服务器中图片存放路径
			String url=picUrl+colours+"/"+name+".jpg";//拼装成指定的路径
			//创建cxf服务 
			JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
			//通过webService服务地址，创建客户端
			String variableWSDL=variableService.selectVariable("PIC_FileVer");
			 Client client = dcf.createClient(variableWSDL);
			 Object[] invoke = null;
		      try {
				 invoke = client.invoke("fileCheck",url);
			} catch (Exception e) {
				e.printStackTrace();
			}
		      String object = (String) invoke[0];
			return object;
		}
			
		  /**
		 *修改数据
	     * @throws IOException 
		 */
		@RequestMapping("/updateAlone.do")
		public void updateAlone(HttpServletRequest request,HttpServletResponse response,Model m,BcThumpic bcThumpic) throws IOException{
			String id = request.getParameter("hiddenId");
			String picname = request.getParameter("upPicName");
			String desctibe = request.getParameter("upDesctibe");
			String colour = request.getParameter("colour");
			       colour=("col".equals(colour))?"1":"0";
			String isRecommend = request.getParameter("upisRecommend");
			String sort = request.getParameter("brandSort");
			String urladdress = request.getParameter("urladdress");
			
			bcThumpic.setId(id);
			bcThumpic.setPicname(picname);
			bcThumpic.setDesctibe(desctibe);
			bcThumpic.setColour(colour);
			bcThumpic.setIsRecommend(isRecommend);
			bcThumpic.setFeatureSort(Integer.parseInt(sort));
			bcThumpic.setUrladdress(urladdress);
			int updateAlone = bcThumpicService.updateAlone(bcThumpic);
			response.getWriter().print(updateAlone);
		}	
		  /**
		   *修改数据
		   * @throws IOException 
		  */
			@RequestMapping("/returnRefresh.do")
			public void returnRefresh(String colour,HttpServletRequest request,HttpServletResponse response) throws IOException{
				//String colour = request.getParameter("colour");
				String colours=("1".equals(colour))?"col":"black";
				String FileUrl=variableService.selectVariable("PIC_bigUrl");//图片在项目发布中存放的位置
				String parYears=variableService.selectVariable("year");//获取最新的年份
				
				 Map<String,Object> map=new HashMap<String,Object>();
				 map.put("year",parYears);
				 map.put("colour",colour);
				 String selectPeriods = bcPictureService.selectPeriods(map);
				 String url=FileUrl+"/"+parYears+"/"+colours+'/'+selectPeriods;
				//创建cxf服务 
				JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
				//通过webService服务地址，创建客户端
				String variableWSDL=variableService.selectVariable("PIC_FileVer");
				 Client client = dcf.createClient(variableWSDL);
				 Object[] invoke=null;
			      try {
					 invoke = client.invoke("queryFolder",url);
				} catch (Exception e) {
					e.printStackTrace();
				}
			      if(invoke.length>0){
			    	   //返回数据处理
			    	@SuppressWarnings("unchecked")
					List<String> list=(List<String>)invoke[0];
			    	  if(list.size()>0){
			    		bcPictureService.scanStorageByThumpic(list,parYears,colours,selectPeriods);
			    	  }else{
				       }
			       } 
				response.getWriter().print("");
			}
			
		  /**
		 *略缩图数据保存
	     * @throws IOException 
		 */
		@RequestMapping("/addPicture.do")
		public void addPicture(HttpServletRequest request,HttpServletResponse response,Model m,BcThumpic bcThumpic) throws IOException{
			bcThumpic.setId(UUIDUtils.getUUID32());
			String colour=("col".endsWith(bcThumpic.getColour()))?"1":"0";
			bcThumpic.setColour(colour);
			String isRecommend=("Y".endsWith(bcThumpic.getIsRecommend()))?"1":"0";
			bcThumpic.setIsRecommend(isRecommend);
			int addInsert = bcThumpicService.addInsert(bcThumpic);
			response.getWriter().print(addInsert);
		}	
	    /**
		*校验注册名是否被使用
		* @throws IOException 
	    */
		@RequestMapping("/checkoutName.do")
		public void checkoutName(HttpServletRequest request,HttpServletResponse response,Model m) throws IOException{
			 response.setContentType("text/html;charset=utf-8");  
	    	 String name = request.getParameter("c");
	    	 boolean variable=true;
	    	 String returndate="";//返回数据
	    	 for(int i=0;i<name.length();i++)  
	    	  {  
	    		 boolean matches = name.substring(i,i+1).matches("[\\u4e00-\\u9fa5]+");
	    		 if(matches){
	    			 variable=false;
	    			 break;  
	    		 }
	    	  }
	    	 if(variable){
		    	 Map<String,Object> map=new HashMap<String,Object>();
				 map.put("picname",name);
				 map.put("colour","1");
		    	 String selectNamecol = bcThumpicService.checkoutName(map);
		    	 if(null==selectNamecol||"".equals(selectNamecol)){
		    		 selectNamecol="0";
		    	 }else{
		    		 selectNamecol="1";
		    	 }
		    	 map.put("colour","0");
		    	 String selectNamebaclk = bcThumpicService.checkoutName(map);
		    	 if(null==selectNamebaclk||"".equals(selectNamebaclk)){
		    		 selectNamebaclk="0";
		    	 }else{
		    		 selectNamebaclk="1";
		    	 } 
		    	returndate= selectNamecol+"_"+selectNamebaclk;
	    	 }else{
	    		returndate="11_11";//有中文
	    	 }
	    	 response.getWriter().print(returndate);   
		}	
		
		}
